package com.tokenplus.thai.components.dialog

import android.os.Bundle
import android.view.*
import android.widget.Toast
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import com.tokenplus.thai.R
import com.tokenplus.thai.databinding.DialogUpdateWalletNameBinding
import com.tokenplus.thai.extend.toBeFocusPoint

class UpdateWalletNameDialog : DialogFragment() {

    //布局
    lateinit var mViewBinding: DialogUpdateWalletNameBinding

    //点击确认监听
    private var mOnConfirmListener: (String) -> Unit = { }

    //内容
    private var mContent: String? = null

    companion object {
        fun showDialog(
            fragmentManager: FragmentManager,
            content: String?,
            listener: (String) -> Unit = {}
        ) {
            val dialog = UpdateWalletNameDialog()
            dialog.mContent = content
            dialog.mOnConfirmListener = listener
            dialog.showNow(fragmentManager, UpdateWalletNameDialog::class.java.simpleName)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View {
        dialog?.requestWindowFeature(Window.FEATURE_NO_TITLE)
        mViewBinding =
            DialogUpdateWalletNameBinding.inflate(layoutInflater)
        return mViewBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initSubViews()
        dialog?.setCancelable(false)
        dialog?.setCanceledOnTouchOutside(false)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NO_TITLE, R.style.Dialog)
    }

    override fun onStart() {
        super.onStart()

        dialog?.window?.let {
            it.attributes.gravity = Gravity.CENTER
            it.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        }

        //更新内容
        mViewBinding.editWalletName.setText(mContent)

        //光标聚集
        mViewBinding.editWalletName.toBeFocusPoint()
    }

    private fun initSubViews() {
        mViewBinding.textWalletNameCancel.setOnClickListener {
            dismiss()
        }
        mViewBinding.textWalletNameConfirm.setOnClickListener {
            val inputValue = mViewBinding.editWalletName.text.toString().trim()
            if (inputValue.isNotBlank()) {
                mOnConfirmListener.invoke(inputValue)
                dismiss()
            } else {
                Toast.makeText(
                    context,
                    getString(R.string.input_please_enter),
                    Toast.LENGTH_SHORT
                ).show()
            }
        }
    }
}